import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Equal } from 'typeorm';
import { User } from '@/entity/users/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  verifyCaptcha(inputCaptcha: string, sessionCaptcha: string): boolean {
    // 验证用户输入的验证码是否正确
    const checkoutInput = inputCaptcha && typeof inputCaptcha === 'string';
    const checkCaptcha = sessionCaptcha && typeof sessionCaptcha === 'string';
    if (checkoutInput && checkCaptcha) {
      return inputCaptcha.toLowerCase() === sessionCaptcha.toLowerCase();
    } else {
      return false;
    }
  }

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: number): Promise<User | null> {
    return this.usersRepository.findOneBy({ id });
  }

  async findOneByName(username: string): Promise<User | undefined> {
    return this.usersRepository.findOneBy({ username });
  }

  async remove(id: number): Promise<void> {
    await this.usersRepository.delete(id);
  }

  async addUser(data: User): Promise<any> {
    await this.usersRepository.save(data);
  }

  async upateUser(
    id: number | string,
    data: Partial<User>,
  ): Promise<User | undefined> {
    // 使用 TypeORM 的 update 方法来更新数据
    await this.usersRepository.update(id, { ...data, upatedAt: new Date() });
    // 根据 id 查找并返回更新后的用户信息
    if (typeof id === 'string') {
      const numericId = parseInt(id);
      return this.usersRepository.findOne({ where: { id: numericId } });
    }
    if (typeof id === 'number') {
      return this.usersRepository.findOne({ where: { id } });
    }
  }

  async findReportsHasPublishId({
    publishId,
    userId,
  }: {
    publishId: string;
    userId: string;
  }) {
    return this.usersRepository
    .createQueryBuilder('users')
    .where('users.id = :userId')
    .andWhere('(users.reports IS NOT NULL AND JSON_CONTAINS(users.reports, :publishId))', { userId, publishId: JSON.stringify(publishId) })
    .getMany();
  }

  async findCollectsHasPublishId({
    publishId,
    userId,
  }: {
    publishId: string;
    userId: string;
  }) {
    return this.usersRepository
      .createQueryBuilder('users')
      .where('users.id = :userId')
      .andWhere('(users.collects IS NOT NULL AND JSON_CONTAINS(users.collects, :publishId))', { userId, publishId: JSON.stringify(publishId) })
      .getMany();
  }

  async findRocketHasPublishId({
    publishId,
    userId,
  }: {
    publishId: string;
    userId: string;
  }) {
    return this.usersRepository
    .createQueryBuilder('users')
    .where('users.id = :userId')
    .andWhere('(users.rocket IS NOT NULL AND JSON_CONTAINS(users.rocket, :publishId))', { userId, publishId: JSON.stringify(publishId) })
    .getMany();
  }
}
